package dev.gokhana.sse.service;

import dev.gokhana.sse.model.LiveScore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class LiveScoreHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(LiveScoreHandler.class);

    private List<Consumer<LiveScore>> listeners = new CopyOnWriteArrayList<>();

    public void subscribe(Consumer<LiveScore> listener) {
        listeners.add(listener);
        LOGGER.info("New one added, total consumer: {}", listeners.size());
    }

    public void unSubscribe(Consumer<LiveScore> listener) {
        listeners = listeners.stream().filter(l -> l != listener).collect(Collectors.toList());
        LOGGER.info("one deleted, total consumer: {}", listeners.size());
    }

    public void publish(LiveScore liveScore) {
        LOGGER.info("Processing live score: {}", liveScore);
        listeners.forEach(listener -> listener.accept(liveScore));
    }

//    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES)
    public void autoPublish() {
        LiveScore liveScore = new LiveScore("Barcelona", "Real Madrid", 0, 1, new Date());
        publish(liveScore);
    }
}